package com.lifeverse.factory.type;

import com.lifeverse.entity.LifeEntity;
import com.lifeverse.entity.enums.LifeEntityType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 城市生命体创建器
 * 专门创建城市类型的生命体
 */
@Slf4j
@Component
public class UrbanLifeEntityCreator implements LifeEntityCreator {
    
    @Override
    public LifeEntity create(String name, String description, Map<String, Object> configuration) {
        log.info("Creating urban life entity: {}", name);
        
        LifeEntity entity = new LifeEntity();
        entity.setType(LifeEntityType.URBAN);
        
        // 设置城市生命体特有的初始属性
        setupUrbanAttributes(entity, configuration);
        
        return entity;
    }
    
    @Override
    public LifeEntity clone(LifeEntity originalEntity, String newName, double variationLevel) {
        log.info("Cloning urban life entity: {} to {}", originalEntity.getName(), newName);
        
        LifeEntity clonedEntity = new LifeEntity();
        clonedEntity.setType(LifeEntityType.URBAN);
        
        // 复制原始城市的属性
        copyUrbanAttributes(clonedEntity, originalEntity);
        
        return clonedEntity;
    }
    
    @Override
    public boolean validateConfiguration(Map<String, Object> configuration) {
        if (configuration == null) {
            return true; // 允许空配置，使用默认值
        }
        
        // 验证城市特有配置
        if (configuration.containsKey("population")) {
            Object population = configuration.get("population");
            if (!(population instanceof Number) || ((Number) population).longValue() < 0) {
                return false;
            }
        }
        
        if (configuration.containsKey("area")) {
            Object area = configuration.get("area");
            if (!(area instanceof Number) || ((Number) area).doubleValue() <= 0) {
                return false;
            }
        }
        
        if (configuration.containsKey("gdp")) {
            Object gdp = configuration.get("gdp");
            if (!(gdp instanceof Number) || ((Number) gdp).doubleValue() < 0) {
                return false;
            }
        }
        
        if (configuration.containsKey("sustainabilityIndex")) {
            Object index = configuration.get("sustainabilityIndex");
            if (!(index instanceof Number)) {
                return false;
            }
            double value = ((Number) index).doubleValue();
            if (value < 0 || value > 100) {
                return false;
            }
        }
        
        return true;
    }
    
    @Override
    public Map<String, Object> getDefaultConfiguration() {
        return Map.of(
                "population", 500000L,
                "area", 100.0, // 平方公里
                "gdp", 5000000000.0, // 50亿
                "cityType", "Metropolitan",
                "developmentLevel", "Developing",
                "sustainabilityIndex", 60.0,
                "smartCityLevel", "Intermediate",
                "infrastructureQuality", "Good",
                "publicServiceLevel", "Standard"
        );
    }
    
    /**
     * 设置城市生命体特有属性
     */
    private void setupUrbanAttributes(LifeEntity entity, Map<String, Object> configuration) {
        Map<String, Object> config = configuration != null ? configuration : getDefaultConfiguration();
        
        // 根据人口规模设置不同的初始能力值
        long population = ((Number) config.getOrDefault("population", 500000L)).longValue();
        setupPopulationBasedAttributes(entity, population);
        
        // 根据城市类型调整特性
        String cityType = (String) config.getOrDefault("cityType", "Metropolitan");
        adjustAttributesByCityType(entity, cityType);
        
        // 根据可持续发展指数调整健康度
        double sustainabilityIndex = ((Number) config.getOrDefault("sustainabilityIndex", 60.0)).doubleValue();
        adjustHealthBySustainability(entity, sustainabilityIndex);
        
        // 根据GDP调整智慧分数
        double gdp = ((Number) config.getOrDefault("gdp", 5000000000.0)).doubleValue();
        adjustWisdomByGDP(entity, gdp);
        
        // 城市生命体通常具有很强的协作能力（公共服务、基础设施协调）
        entity.setCollaborationScore(BigDecimal.valueOf(85.0));
    }
    
    /**
     * 根据人口规模设置属性
     */
    private void setupPopulationBasedAttributes(LifeEntity entity, long population) {
        if (population < 100000) {
            // 小城市：灵活但资源有限
            entity.setCreativityScore(BigDecimal.valueOf(65.0));
            entity.setWisdomScore(BigDecimal.valueOf(60.0));
            entity.setEnergyLevel(BigDecimal.valueOf(90.0));
        } else if (population < 500000) {
            // 中等城市：平衡发展
            entity.setCreativityScore(BigDecimal.valueOf(70.0));
            entity.setWisdomScore(BigDecimal.valueOf(70.0));
            entity.setEnergyLevel(BigDecimal.valueOf(85.0));
        } else if (population < 2000000) {
            // 大城市：资源丰富但复杂
            entity.setCreativityScore(BigDecimal.valueOf(80.0));
            entity.setWisdomScore(BigDecimal.valueOf(80.0));
            entity.setEnergyLevel(BigDecimal.valueOf(75.0));
        } else {
            // 超大城市：高度复杂但能力强
            entity.setCreativityScore(BigDecimal.valueOf(90.0));
            entity.setWisdomScore(BigDecimal.valueOf(90.0));
            entity.setEnergyLevel(BigDecimal.valueOf(70.0));
        }
    }
    
    /**
     * 根据城市类型调整属性
     */
    private void adjustAttributesByCityType(LifeEntity entity, String cityType) {
        BigDecimal creativityMultiplier = BigDecimal.ONE;
        BigDecimal wisdomMultiplier = BigDecimal.ONE;
        BigDecimal collaborationMultiplier = BigDecimal.ONE;
        
        switch (cityType.toLowerCase()) {
            case "tech_hub" -> {
                creativityMultiplier = BigDecimal.valueOf(1.3);
                wisdomMultiplier = BigDecimal.valueOf(1.2);
                collaborationMultiplier = BigDecimal.valueOf(1.1);
            }
            case "industrial" -> {
                creativityMultiplier = BigDecimal.valueOf(0.9);
                wisdomMultiplier = BigDecimal.valueOf(1.3);
                collaborationMultiplier = BigDecimal.valueOf(1.2);
            }
            case "cultural" -> {
                creativityMultiplier = BigDecimal.valueOf(1.4);
                wisdomMultiplier = BigDecimal.valueOf(1.1);
                collaborationMultiplier = BigDecimal.valueOf(1.3);
            }
            case "financial" -> {
                creativityMultiplier = BigDecimal.valueOf(1.1);
                wisdomMultiplier = BigDecimal.valueOf(1.4);
                collaborationMultiplier = BigDecimal.valueOf(1.0);
            }
            case "tourist" -> {
                creativityMultiplier = BigDecimal.valueOf(1.2);
                wisdomMultiplier = BigDecimal.valueOf(1.0);
                collaborationMultiplier = BigDecimal.valueOf(1.4);
            }
            case "educational" -> {
                creativityMultiplier = BigDecimal.valueOf(1.3);
                wisdomMultiplier = BigDecimal.valueOf(1.5);
                collaborationMultiplier = BigDecimal.valueOf(1.3);
            }
        }
        
        entity.setCreativityScore(entity.getCreativityScore().multiply(creativityMultiplier));
        entity.setWisdomScore(entity.getWisdomScore().multiply(wisdomMultiplier));
        entity.setCollaborationScore(entity.getCollaborationScore().multiply(collaborationMultiplier));
    }
    
    /**
     * 根据可持续发展指数调整健康度
     */
    private void adjustHealthBySustainability(LifeEntity entity, double sustainabilityIndex) {
        // 可持续发展指数直接影响城市的健康度
        BigDecimal healthScore = BigDecimal.valueOf(sustainabilityIndex * 1.2); // 转换为0-120范围
        if (healthScore.compareTo(BigDecimal.valueOf(100)) > 0) {
            healthScore = BigDecimal.valueOf(100);
        }
        entity.setHealthScore(healthScore);
    }
    
    /**
     * 根据GDP调整智慧分数
     */
    private void adjustWisdomByGDP(LifeEntity entity, double gdp) {
        BigDecimal currentWisdom = entity.getWisdomScore();
        
        if (gdp < 1000000000) { // 10亿以下
            entity.setWisdomScore(currentWisdom.multiply(BigDecimal.valueOf(0.8)));
        } else if (gdp < 10000000000L) { // 100亿以下
            entity.setWisdomScore(currentWisdom);
        } else if (gdp < 100000000000L) { // 1000亿以下
            entity.setWisdomScore(currentWisdom.multiply(BigDecimal.valueOf(1.2)));
        } else {
            entity.setWisdomScore(currentWisdom.multiply(BigDecimal.valueOf(1.4)));
        }
    }
    
    /**
     * 复制城市属性
     */
    private void copyUrbanAttributes(LifeEntity clonedEntity, LifeEntity originalEntity) {
        // 复制基本属性
        clonedEntity.setWisdomScore(originalEntity.getWisdomScore());
        clonedEntity.setCreativityScore(originalEntity.getCreativityScore());
        clonedEntity.setCollaborationScore(originalEntity.getCollaborationScore());
        clonedEntity.setEnergyLevel(originalEntity.getEnergyLevel());
        clonedEntity.setHealthScore(originalEntity.getHealthScore());
        
        // 复制配置信息
        clonedEntity.setConfiguration(originalEntity.getConfiguration());
    }
}